package controllers;

import helpers.ItuneXMLUrlHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.Software;
import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheManager;
import crawlers.CrawlerItuneXML;

public class Sitemap extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		
		response.setHeader("Cache-Control", "public, max-age=86400");
		response.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		
		response.setCharacterEncoding("UTF-8");
		
		//Set variable
		ArrayList<Software> softwares = new ArrayList<Software>();
		ItuneXMLUrlHelper urlHelper = new ItuneXMLUrlHelper();
		//Set cache
        Cache cache=null;
        String cachename = "sitemap";
        try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           e.printStackTrace();
        }
        System.out.println(cachename);
        if (cache.containsKey(cachename)) {
        	softwares = (ArrayList<Software>) cache.get(cachename);
        	System.out.println("softwares: cache print");
        } else {
        	System.out.println(urlHelper.getUrl());
        	softwares = (ArrayList<Software>) CrawlerItuneXML.getXML(urlHelper.getUrl());
        	if (softwares.size() > 0) {
        		cache.put(cachename, softwares);
        	}
	        System.out.println("softwares: Data print");
        }
		
        request.setAttribute("softwares", softwares);
		try {
			request.getRequestDispatcher("/pages/sitemap.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
